package com.building.util;/**
 * Created by LH on 2021/3/4.
 */

import com.alibaba.fastjson.JSONObject;
import com.sun.deploy.net.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.*;

/**
 * @ClassName CheckSumUtil
 * @Description: TODO
 * @Author LH
 * @Date 2021/3/4
 **/
@Slf4j
public class CheckSumUtil {
    private static final String path = "https://api.netease.im/sms/sendcode.action";
    private static final String appKey = "1bd5e9899dff0d78c286ecb1f21dcdd3";
    private static final String appSecret = "564baec24ba8";

    public static String sendMessage(String phone) throws Exception {
        if(1==1){
            return "123";
        }
        log.info("发送短信给："+phone);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(path);
        Integer nonce = new Random().nextInt(999999);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumUtil.getCheckSum(appSecret, nonce.toString(), curTime);//获取CheckSum

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce.toString());
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("mobile", phone));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        CloseableHttpResponse execute = httpClient.execute(httpPost);
        // 执行请求
        String result = EntityUtils.toString(execute.getEntity(), "utf-8");

        JSONObject json = JSONObject.parseObject(result);

        log.info("发送短信成功，返回参数为："+result);
        if(json.getInteger("code") == 200){
            return json.getString("obj");
        }
        return "";
    }


    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    // 计算并获取CheckSum
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    // 计算并获取md5值
    public static String getMd5(String requestBody) {
        return encode("md5", requestBody);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
}
